package com.ts.api.http.feedback;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.log.LogLevel;
import com.gitee.apanlh.util.net.http.HttpClientBuilder;
import com.gitee.apanlh.util.net.http.HttpResponse;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.http.HttpMethod;
import com.gitee.apanlh.web.model.vo.RequestVO;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 小红书
 *
 * https://doc.weixin.qq.com/doc/w3_AZIAygYhAPM92euemqrSE6y5Zacc3?scode=ANAAyQcbAAgvpM2sPLAa0A_wZkAMc
 *
 * https://doc.weixin.qq.com/doc/w3_AQIASAZ7AHULHq6sqkJQv2wXavaZi?scode=ANAAyQcbAAgSYrkLMSAQIASAZ7AHU&is_external=0&commentVersion=1687229482000&doc_title=%E3%80%90%E5%A4%96%E9%83%A8%E3%80%91%E5%9B%9E%E4%BC%A0%E8%BD%AC%E5%8C%96API%E6%8E%A5%E5%85%A5%E6%96%87%E6%A1%A3&from_wecom=1
 *
 * @author caoxin
 */
@Component
// 由于accessToken会被覆盖，所以暂时只在生产环境使用
@Profile("prod")
public class XiaoHongShuFeedbackHandler implements FeedbackHandler {

    @Override
    public boolean match(RequestVO requestVO) {
        return Eq.str(requestVO.getStr("type"), "xiaohongshu");
    }

    @Override
    public Object feedback(RequestVO requestVO) {
        String clickId = requestVO.getStr("clickId");
        if (ValidParam.isNotEmpty(clickId)) {
            this.leads("101", clickId);
        }
        return new HashMap<>();
    }

    /** 广告主id */
    private static final String ADVERTISER_ID = "7130904";

    public void leads(String eventType, String clickId) {
        String accessToken = getAccessToken();
        /** 接口地址 */
        String url = "https://adapi.xiaohongshu.com/api/open/common";

        Map<String, Object> bodyMap = MapUtils.newHashMap();
        bodyMap.put("advertiser_id", ADVERTISER_ID);
        bodyMap.put("method", "aurora.leads");
        bodyMap.put("access_token", accessToken);
        bodyMap.put("event_type", eventType);
        bodyMap.put("conv_time", System.currentTimeMillis());
        bodyMap.put("click_id", clickId);

        String reqJson = JSONObject.toJSONString(bodyMap);

        HttpResponse build = HttpClientBuilder.builder(url, HttpMethod.POST)
                .withBodyJson(reqJson)
                .withHeader((headerMap) -> {
                    headerMap.put("Content-Type", "application/json");
                })
                .withLogLevel(LogLevel.WARN)
                .withErrorLogLevel(LogLevel.WARN)
                .build();
        String str = build.getStr();
        JSONObject jsonObject = JSONObject.parseObject(str);
    }

    @Autowired
    private RedissonClient redissonClient;
    private static final String ACCESS_TOKEN_REDIS_KEY_NAME = "com.ts.api.http.feedback.XiaoHongShuFeedbackHandler:accessToken";

    private String getAccessToken() {
        RBucket<String> bucket = redissonClient.getBucket(ACCESS_TOKEN_REDIS_KEY_NAME);

        {
            // 从 redis 中获取 accessToken
            String accessToken = bucket.get();
            // 有获取到 accessToken 则直接返回
            if (ValidParam.isNotEmpty(accessToken)) {
                return accessToken;
            }
        }

        // 加分布式锁
        RLock lock = redissonClient.getLock("com.ts.api.http.feedback.XiaoHongShuFeedbackHandler:lock");
        lock.lock(10, TimeUnit.SECONDS);
        try {
            // 双重检测
            {
                // 从 redis 中获取 accessToken
                String accessToken = bucket.get();
                // 有获取到 accessToken 则直接返回
                if (ValidParam.isNotEmpty(accessToken)) {
                    return accessToken;
                }
            }

            // 通过接口获取 accessToken
            String accessToken = this.getAccessToken0();
            if (ValidParam.isNotEmpty(accessToken)) {
                bucket.set(accessToken, Duration.ofSeconds(3000L));
            }
            return accessToken;
        } finally {
            lock.unlock();
        }
    }

    private String getAccessToken0() {
        /** 接口地址 */
        String url = "https://adapi.xiaohongshu.com/api/open/common";

        Map<String, Object> bodyMap = MapUtils.newHashMap();
        bodyMap.put("advertiser_id", ADVERTISER_ID);
        bodyMap.put("method", "oauth.getAccessToken");

        String reqJson = JSONObject.toJSONString(bodyMap);

        HttpResponse build = HttpClientBuilder.builder(url, HttpMethod.POST)
                .withBodyJson(reqJson)
                .withHeader((headerMap) -> {
                    headerMap.put("Content-Type", "application/json");
                })
                .withLogLevel(LogLevel.WARN)
                .withErrorLogLevel(LogLevel.WARN)
                .build();
        String str = build.getStr();
        JSONObject jsonObject = JSONObject.parseObject(str);
        JSONObject data = jsonObject.getJSONObject("data");
        String string = data.getString("access_token");
        return string;
    }

}
